package cn.server.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.server.IBusiness;
import cn.server.util.SQLUtil;
import cn.server.util.ServerConfUtil;

public abstract class AbstractBusiness implements IBusiness {

	protected File requestFile;

	protected List<String> list = null;

	protected static final String PREFIX = "config/receive/%s";

	private static final Log logger = LogFactory.getLog(AbstractBusiness.class);

	private byte[] defaultfail = "fail".getBytes();

	@Override
	public byte[] doBusiness(byte[] request, Map<String, String> headMap) {
		if (request == null)
			return defaultfail;
		try {
			requestFile = new File(String.format(PREFIX, UUID.randomUUID().toString()));
			FileUtils.writeByteArrayToFile(requestFile, request);
			list = FileUtils.readLines(requestFile);
			for (int i = 0; i < list.size(); i++) {
				String line = list.get(i).trim();
				if (isIginore(line))
					continue;
				try {
					List<Map<String, Object>> list = dealData(line, headMap);
					if (list != null){
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> map = list.get(j);
							SQLUtil.insertByMap(ServerConfUtil.getSql("insertmonitor"), map);
						}
					}
				} catch (Throwable e) {
					logger.error("error insert into db!", e);
				}
			}
			// TODO 返回响应报文
			return "success".getBytes();
		} catch (Throwable e) {
			logger.error("error write request to file!", e);
		} finally {
			FileUtils.deleteQuietly(requestFile);
		}
		return defaultfail;
	}

	protected BigDecimal calulate(String value) {
		if (value.endsWith("KB"))
			return new BigDecimal(value.replace("KB", "")).multiply(new BigDecimal(1000));
		if (value.endsWith("B"))
			return new BigDecimal(value.replace("B", ""));
		if (value.endsWith("b"))
			return new BigDecimal(value.replace("b", "")).divide(new BigDecimal(8));
		return null;
	}

	public abstract boolean isIginore(String line);

	public abstract List<Map<String, Object>> dealData(String line, Map<String, String> headMap);
}